package com.jl.sms.cdma;

import java.util.Arrays;

import com.jl.util.Calculator;
import com.jl.util.HexUtil;

public class Address implements Parameter{
	
	private int type;
	private String address;
	private byte[] allValue;

	public Address(int type,String address){
		this.type = type;
		this.address = address.trim();
		
		String temp = this.address.replaceAll("0", "A");
		temp = "00" + HexUtil.toHexXX(temp.length()).substring(1) + temp;
		if (temp.length() % 2 != 0)
			temp += "0";

		byte[] bl = Calculator.lsh(HexUtil.parseHexToByteArray(temp), 2);
		allValue = new byte[bl.length + 2];
		allValue[0] = (byte) (type & 0xFF);
		allValue[1] = (byte) (bl.length & 0xFF);
		System.arraycopy(bl, 0, allValue, 2, bl.length);
	}

	public Address(byte[] value) {
		allValue = value.clone();
		type = allValue[0];
		
		byte[] res = Arrays.copyOfRange(allValue, 2, allValue.length);
		res = Calculator.rsh(res, 2);
		String str = HexUtil.toHexCompact(res);
		str = str.substring(3);
		str = str.replaceAll("A|a", "0");
		address = str.substring(0, (res[1] >> 4) & 0x0F);
	}

	@Override
	public byte getID() {
		return (byte) type;
	}

	@Override
	public byte[] getData() {
		return Arrays.copyOfRange(allValue, 2, allValue.length);
	}

	@Override
	public byte[] value() {
		return allValue;
	}

	@Override
	public String valueAsString() {
		return address;
	}

}
